<?php

namespace App\Criteria;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Class SearchableCriteria.
 *
 * @package namespace App\Criteria;
 */
class SearchableCriteria implements CriteriaInterface
{
    protected $request;

    protected $characters = ['like', 'eq', 'egt', 'elt', 'join'];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Apply criteria in query repository
     *
     * @param string              $model
     * @param RepositoryInterface $repository
     *
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $where = [];
        array_walk($this->characters, function($character) use (&$where) {
            optional($this->request->input($character), function($items) use (&$where, $character) {
                array_walk($items, function($value, $name) use (&$where, $character) {
                    if (!$value) {
                        return false;
                    }
                    $character == 'like' && $value = "%{$value}%";
                    array_push($where, [$name, $this->translate($character), $value]);
                });
            });
        });
        return $model->where($where);
    }

    protected function translate($character)
    {
        switch ($character) {
            case 'like':
                return 'like';
                break;
            case 'eq':
                return '=';
                break;
            case 'egt':
                return '>=';
                break;
            case 'elt':
                return '<=';
                break;
            default:
                return '=';
                break;
        }
    }
}
